package com.yw.wanandroid.ui.vm

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.yw.wanandroid.base.BaseNetBean
import com.yw.wanandroid.model.HomeArticleBean
import com.yw.wanandroid.model.HomeTopArticleModel
import com.yw.wanandroid.net.NetClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class HomeViewModel : ViewModel() {
    val TAG: String = HomeViewModel::javaClass.name
    val toplist = MutableLiveData<ArrayList<HomeTopArticleModel>>()
    val articleList = MutableLiveData<ArrayList<HomeTopArticleModel>>()
    var page: Int = 0


    fun getHomeTopArticle() {
        NetClient.getHomeApi().getTopArticleList()
            .enqueue(object : Callback<BaseNetBean<ArrayList<HomeTopArticleModel>>> {
                override fun onResponse(
                    call: Call<BaseNetBean<ArrayList<HomeTopArticleModel>>>,
                    response: Response<BaseNetBean<ArrayList<HomeTopArticleModel>>>
                ) {
                    val list = response.body()?.data
                    list?.forEach {
                        it.top = 1
                    }
                    toplist.value = list!!
                }

                override fun onFailure(
                    call: Call<BaseNetBean<ArrayList<HomeTopArticleModel>>>,
                    t: Throwable
                ) {
                    Log.d(TAG, "onFailure:${t.message}")
                }
            })
    }

    fun getHomeArticle(isRefresh: Boolean) {
        if (isRefresh) {
            page = 0
        } else {
            page++
        }
        NetClient.getHomeApi().getArticleList(page)
            .enqueue(object : Callback<BaseNetBean<HomeArticleBean>> {
                override fun onResponse(
                    call: Call<BaseNetBean<HomeArticleBean>>,
                    response: Response<BaseNetBean<HomeArticleBean>>
                ) {
                    if (response.body()?.errorCode == 0) {
                        articleList.value = response.body()?.data?.datas
                    }
                }

                override fun onFailure(
                    call: Call<BaseNetBean<HomeArticleBean>>,
                    t: Throwable
                ) {
                    Log.d(TAG, "onFailure:${t.message}")
                }
            })
    }
}